from sqlalchemy.orm import Session
from sqlalchemy import or_
from app.models.user import User
from app.schemas.user import UserCreate
from datetime import datetime
from passlib.context import CryptContext
from typing import Optional

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)

def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)

def get_user_by_email(db: Session, email: str) -> Optional[User]:
    return db.query(User).filter(User.email == email).first()

def get_user_by_openid(db: Session, openid: str) -> Optional[User]:
    return db.query(User).filter(User.openid == openid).first()

def get_user_by_unionid(db: Session, unionid: str) -> Optional[User]:
    return db.query(User).filter(User.unionid == unionid).first()

def get_user_by_id(db: Session, user_id: int) -> Optional[User]:
    return db.query(User).filter(User.id == user_id).first()

def create_user(db: Session, user_data: UserCreate) -> User:
    hashed_password = get_password_hash(user_data.password)
    db_user = User(
        email=user_data.email,
        password=hashed_password,
        nickname=user_data.nickname,
        login_type="email",
        avatar=user_data.avatar,
        gender=user_data.gender,
        status=user_data.status
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def create_or_update_wechat_user(
    db: Session, 
    unionid: str, 
    openid: str, 
    nickname: str,
    avatar: str,
    gender: int
) -> User:
    # 先尝试查找现有用户
    user = db.query(User).filter(
        or_(User.unionid == unionid, User.openid == openid)
    ).first()
    
    if user:
        # 更新现有用户
        user.unionid = unionid
        user.openid = openid
        user.nickname = nickname
        user.avatar = avatar
        user.gender = gender
        user.last_login_at = datetime.utcnow()
        db.commit()
        db.refresh(user)
        return user
    else:
        # 创建新用户
        db_user = User(
            unionid=unionid,
            openid=openid,
            nickname=nickname,
            avatar=avatar,
            gender=gender,
            login_type="wechat",
            last_login_at=datetime.utcnow()
        )
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
        return db_user

def update_last_login(db: Session, user: User) -> User:
    user.last_login_at = datetime.utcnow()
    db.commit()
    db.refresh(user)
    return user 